//
//  AppDelegate.swift
//  HSBellManage
//
//  Created by Bestsch on 16/10/18.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit
//import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    struct ShareIdentity {
        
        static var  WeChatAppId: String {
            #if EDUMANAGE
                return "wx4950fe060a30c230"
            #elseif HSEDUMANAGE
                return "wx68b343ffb2dd8875"
            #elseif TXEDUMANAGE
                return "wx7ed14aa280770dfa"
            #else
                return ""
            #endif
        }
        static var  WeChatSecret: String {
            #if EDUMANAGE
                return "229e590815792e196c68297f4a315847"
            #elseif HSEDUMANAGE
                return "229e590815792e196c68297f4a315847"
            #elseif TXEDUMANAGE
                return "229e590815792e196c68297f4a315847"
            #else
                return ""
            #endif
        }
        static var QQAppId: String {
            #if EDUMANAGE
                return "1105388450"
            #elseif HSEDUMANAGE
                return "1105388450"
            #elseif TXEDUMANAGE
                return "1105388450"
            #else
                return ""
            #endif
        }
        static var QQAppSecret: String {
            #if EDUMANAGE
                return "t77v0QESMYkK9mQY"
            #elseif HSEDUMANAGE
                return "t77v0QESMYkK9mQY"
            #elseif TXEDUMANAGE
                return "t77v0QESMYkK9mQY"
            #else
                return ""
            #endif
        }
        static var WeiboAppKey: String {
            #if EDUMANAGE
                return "1427473368"
            #elseif HSEDUMANAGE
                return "1427473368"
            #elseif TXEDUMANAGE
                return "1427473368"
            #else
                return ""
            #endif
        }
        static var WeiboAppSecret: String {
            #if EDUMANAGE
                return "276a3f866f0f1a90f7255ba193c504ef"
            #elseif HSEDUMANAGE
                return "276a3f866f0f1a90f7255ba193c504ef"
            #elseif TXEDUMANAGE
                return "276a3f866f0f1a90f7255ba193c504ef"
            #else
                return ""
            #endif
        }
    }
    
    struct BaiDu {
        static var crabKey: String {
            #if EDUMANAGE
                return "ab40c52904c6afbb"
            #elseif HSEDUMANAGE
                return "8cd12283a87aa2f6"
            #elseif TXEDUMANAGE
                return "c5c89b448bd0f5a4"
            #elseif BELLSUPER
                return "b7d785f0ed6cc52e"
            #elseif HSSUPER
                return "4b77c8e235e926e0"
            #elseif TXSUPER
                return "448390d15e83c490"
            #elseif HYEDUMANAGE
                return "05c2c9ff92168065"
            #elseif HYCLOUDSUPER
                return "9556cd16c81149f8"
            #endif
        }
        
        static var statKey: String {
            #if EDUMANAGE
                return "6afdd2a8d1"
            #elseif HSEDUMANAGE
                return "2523cc0b3e"
            #elseif TXEDUMANAGE
                return "41914b6239"
            #elseif BELLSUPER
                return "2da3a3da44"
            #elseif HSSUPER
                return "b88e913f79"
            #elseif TXSUPER
                return "387e1776c5"
            #elseif HYEDUMANAGE
                return "ea4e01c01d"
            #elseif HYCLOUDSUPER
                return "a2eda16a3d"
            #endif
        }
        
    }
    
    struct UMSocial {
        static var socialKey: String {
            #if EDUMANAGE
                return "57561ad1e0f55a62ab00198f"
            #elseif HSEDUMANAGE
                return "58056d7fe0f55a8a9900155f"
            #elseif TXEDUMANAGE
                return "582199961c5dd0182f00101f"
            #else
                return ""
            #endif
        }
    }
    
    func initBaiDu() {
        
        let statTracker: BaiduMobStat = BaiduMobStat.default()
        statTracker.enableDebugOn = true
        statTracker.enableExceptionLog = false
        statTracker.start(withAppId: BaiDu.statKey)
        
        let report: CrabCrashReport = CrabCrashReport.sharedInstance() as! CrabCrashReport
        report.initCrashReporter(withAppKey: BaiDu.crabKey, andVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String!, andChannel: "App Store")
        let user = getUserPojo()
        if user.userid != nil && user.userid != "" {
            report.setAppUsername("\(user.userid)")
        }
        
    }
    
    func InitUm() {
        
        /**
         友盟分享
         */
        UMSocialData.setAppKey(UMSocial.socialKey)
        UMSocialData.openLog(true)
        /**
         配置第三方分享的id－－－微信，qq，微博
         */
        UMSocialWechatHandler.setWXAppId(ShareIdentity.WeChatAppId, appSecret: ShareIdentity.WeChatSecret, url: "http://www.umeng.com/social")
        
        #if EDUMANAGE
            UMSocialQQHandler.setQQWithAppId(ShareIdentity.QQAppId, appKey: ShareIdentity.QQAppSecret, url: "http://www.umeng.com/social")
            UMSocialSinaSSOHandler.openNewSinaSSO(withAppKey: ShareIdentity.WeiboAppKey, secret: ShareIdentity.WeiboAppSecret, redirectURL: "http://sns.whalecloud.com/sina2/callback")
            UMSocialConfig.hiddenNotInstallPlatforms([UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToWechatTimeline,UMShareToWechatSession])
        #else
            UMSocialConfig.hiddenNotInstallPlatforms([UMShareToWechatTimeline,UMShareToWechatSession])
        #endif
        
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        #if HYCLOUDSUPER
            print("HYCLOUDSUPER")
        #endif
        
        application.statusBarStyle = UIStatusBarStyle.lightContent
        
        let user = getUserPojo()
        
        #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE || HYEDUMANAGE
            InitUm()
            if user.userid != nil && user.userid != "" {
                goToMain()
            }else {
                gotoLogin()
            }
        #elseif BELLSUPER || HSSUPER || TXSUPER || HYCLOUDSUPER
            if user.UpperCode != nil && user.UpperCode != "" {
                goToSuper()
            }else {
                gotoLogin()
            }
        #endif
        
        initBaiDu()
        return true
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        let result = UMSocialSnsService.handleOpen(url)
        if !result {
            
        }
        return result
    }
    
    /**
     跳转到登录
     */
    func gotoLogin() {
        let loginVC = LoginViewController()
        let navigationVC = UINavigationController(rootViewController: loginVC)
        self.window?.rootViewController = navigationVC
        self.window?.makeKeyAndVisible()
    }
    /**
     跳转到主页
     */
    func goToMain() {
        //1212 - 改用代码写根视图 由于 铃铛管家tabbar需要2个 而惠山教育管家、桐乡教育管家需要3个tabbar
//        let storyboard = UIStoryboard.init(name: "MainStoryboard", bundle: nil)
//        let mainVC = storyboard.instantiateViewController(withIdentifier: "Main_class")
        
        let mainVC = MianTabBarViewController()
        self.window?.rootViewController = mainVC
        self.window?.makeKey()
    }
    
    func goToSuper() {
        let mainVc = SuperBellViewController()
        let navigationVC = UINavigationController(rootViewController: mainVc)
        
        self.window?.rootViewController = navigationVC
        self.window?.makeKey()
    }
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        //前台
        NotificationCenter.default.post(name: Notification.Name(rawValue: "refreshNotification"), object: nil)
        
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        //        self.saveContext()
    }
    
    // MARK: - Core Data stack
    
    //    lazy var applicationDocumentsDirectory: URL = {
    //        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bestsch.wsl.BellManage" in the application's documents Application Support directory.
    //        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    //        return urls[urls.count-1]
    //    }()
    //
    //    lazy var managedObjectModel: NSManagedObjectModel = {
    //        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    //        let modelURL = Bundle.main.url(forResource: "BellManage", withExtension: "momd")!
    //        return NSManagedObjectModel(contentsOf: modelURL)!
    //    }()
    //
    //    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    //        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    //        // Create the coordinator and store
    //        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    //        let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
    //        var failureReason = "There was an error creating or loading the application's saved data."
    //        do {
    //            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
    //        } catch {
    //            // Report any error we got.
    //            var dict = [String: AnyObject]()
    //            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
    //            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
    //
    //            dict[NSUnderlyingErrorKey] = error as NSError
    //            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
    //            // Replace this with code to handle the error appropriately.
    //            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    //            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
    //            abort()
    //        }
    //
    //        return coordinator
    //    }()
    //
    //    lazy var managedObjectContext: NSManagedObjectContext = {
    //        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    //        let coordinator = self.persistentStoreCoordinator
    //        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    //        managedObjectContext.persistentStoreCoordinator = coordinator
    //        return managedObjectContext
    //    }()
    //
    //    // MARK: - Core Data Saving support
    //
    //    func saveContext () {
    //        if managedObjectContext.hasChanges {
    //            do {
    //                try managedObjectContext.save()
    //            } catch {
    //                // Replace this implementation with code to handle the error appropriately.
    //                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    //                let nserror = error as NSError
    //                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
    //                abort()
    //            }
    //        }
    //    }
    
}

func HYLog<T>(_ message : T, file : String = #file, method: String = #function, lineNumber : Int = #line) {
    
    #if DEBUG
        let fileName = (file as NSString).lastPathComponent
        print("====>fileName:\(fileName)====>line:\(lineNumber)====>method:\(method)====>message:\(message)")
    #endif
}



